/**
 * api/attribute
 */
const sortQB = require('../../../utils/sort-qb')({
    'id-asc': ['id', 'asc'],
    'id-desc': ['id', 'desc'],

    'priority-asc': [
        'priority', 'asc',
        'id', 'asc'
    ],
    'default': [
        'priority', 'desc',
        'id', 'desc'
    ]
});
const weekdays = require('../../../data/weekdays');

module.exports = function(app) {
    const router = app.router;
    const Attribute = app.models.Attribute;
    // const Keyword = app.models.Keyword;
    // const Group = app.models.Group;
    // const KeywordGroup = app.models.KeywordGroup;

    /**
     * @apiVersion 1.0.0
     * @apiGroup Attribute
     * @api {get} /attributes 获取所有标签
     * @apiParam sort=priority-desc 排序 `priority-desc` `priority-asc`
     * @apiSuccessExample Success
     * {
     *     "color": [{...}, {...}]
     * }
     *
     * @apiSampleRequest
     */
    router.get('/attributes', function * () {
        this.query.sort = this.query.sort === 'priority-asc' ? 'ASC' : 'DESC';
        this.body = {
            weekdays: weekdays
        };
    });

    /**
     * @apiVersion 1.0.0
     * @apiGroup Attribute
     * @api {get} /attributes/:type 获取特定的标签列表
     * @apiParam {String} type 属性类型，支持 `gym_tags` `course_tags` `coach_tags` `weekdays` `time_scopes`
     * @apiParam {Number} page_num=1 页码
     * @apiParam {Number} page_size=20 分页大小
     * @apiParam {Number} status 属性开启状态 `0: pending 1: online 2: offline`
     * @apiParam {String} sort 排序，支持：`priority-desc, priority-asc`
     * @apiSuccessExample Success
     * [{
     *     "id": 1,
     *     "name": "红色",
     *     "alias": "#FF0000"
     * }]
     *
     * @apiSampleRequest /attributes/color
     */
    router.get('/attributes/:type', function * () {
        const query = this.query;
        query.status = query.status || 1;

        if(this.params.type === 'weekdays') {
            this.body = weekdays;
            return;
        }
        const attributes = yield Attribute.query((qb) => {
            if(query.status !== 'all') {
                qb.where('status', query.status);
            }
            qb.where('type', this.params.type);
            sortQB(qb, query.sort);
        })
        .fetchItems({
            page_size: query.page_size,
            page_num: query.page_num
        });

        this.body = attributes;
    });

    /**
     * @apiVersion 1.0.0
     * @apiGroup Attribute
     * @api {get} /attributes/:type/:id 获取标签详情
     * @apiParam {String} type 属性类型，支持 `gym_tags` `course_tags` `coach_tags`
     * @apiSuccessExample Success
     * {
     *     "id": 1,
     *     "name": "开业",
     * }
     *
     * @apiSampleRequest /attributes/feature/2
     */
    router.get('/attributes/:type/:id', function * () {
        const attributes = yield Attribute.where({
            type: this.params.type,
            id: this.params.id
        })
        .fetchAll({
            require: false
        });
        if(attributes.models[0]) {
            this.body = attributes.models[0];
        }
    });

    /**
     * @apiVersion 1.0.0
     * @apiGroup Attribute
     * @api {post} /attributes 添加标签
     * @apiParam {String} name 名称
     * @apiParam {String} value 值
     * @apiParam {Number} priority 优先级
     * @apiParam {String} type 属性类型，支持 `gym_tags` `course_tags` `coach_tags`
     * @apiParam {String} [type_name] 类型名称
     * @apiSuccessExample Success
     * {
     *     "id": 1,
     *     "name": "红色",
     *     "value": "#FF0000"
     * }
     *
     * @apiSampleRequest /attributes
     */
    router.post('/attributes', function * () {
        const body = this.request.body;
        const attributes = yield Attribute.where({
            type: body.type,
        })
        .orderBy('id')
        .fetchAll({
            require: false
        });
        const attribute = Attribute.safeForge(body);
        const id = attributes.models.length ? attributes.models[attributes.models.length - 1].get('id') * 2 : 1;
        yield attribute.save({
            id: id
        }, {
            method: 'insert'
        });

        // // 同步关键字
        // const group = yield Group.where({
        //     key: body.type,
        //     type: 'basic'
        // })
        // .fetch();

        // if(group) {
        //     const keyword = Keyword.safeForge({
        //         keyword: attribute.get('name'),
        //         bit_id: attribute.get('id'),
        //         type: 'basic',
        //     });
        //     yield keyword.save();

        //     yield KeywordGroup.safeForge({
        //         keyword_id: keyword.get('id'),
        //         group_id: group.get('id'),
        //         priority: attribute.get('priority')
        //     }).save();
        // }
        this.body = attribute;
    });

    /**
     * @apiVersion 1.0.0
     * @apiGroup Attribute
     * @api {put} /attributes/:id 修改标签
     *
     * @apiParam {String} name 名称
     * @apiParam {String} value 值
     * @apiParam {Number} status 属性开启状态 `0: pending 1: online 2: offline`
     * @apiParam {String} type 属性类型，支持 `feature` `color` `ratio` `style`
     * @apiParam {Number} priority 优先级
     * @apiSuccessExample Success
     * {
     *     "id": 1,
     *     "name": "红色",
     *     "value": "#FF0000"
     * }
     *
     * @apiSampleRequest /attributes/1
     */
    router.put('/attributes/:id', function * () {
        const attribute = yield Attribute.where({
            type: this.request.body.type,
            id: this.params.id
        })
        .save(this.request.body, {
            method: 'update'
        });

        this.body = attribute;
    });
};
